// 楼盘列表页面 四级路由
import { useEffect, useState } from "react";
import {
  ProTable,
} from "@ant-design/pro-components";
import { Button, Switch } from "antd";
import { useDispatch, useSelector } from "react-redux";
// 仓库方法
import {
  pListSet,
  pListItemStateChe,
  editProperty,
  delProperty1,
  searchProperty1,
  deleRow,
} from "../../../../../store/reducer/propertylist";
import { Form, Input, Select, message } from "antd";
import { useNavigate } from "react-router-dom";
import { Space } from "antd";
import request from "../../../../../http/request";

export default () => {
  const dis = useDispatch();
  const nav = useNavigate();

  useEffect(() => {
    if (!localStorage.getItem("pList")) {
      request.get("/api/propertiesList").then((res) => {
        console.log(res.propertiesList);
        dis(pListSet(res.propertiesList));
      });
    }
  }, []);

  const list = useSelector((state) => {
    return state.propertylist.pList;
  });

  // console.log(list);

  const tableListDataSource = [];

  list?.forEach((item, index) => {
    for (let i = 1; i < 3; i += 1) {
      return tableListDataSource.push({
        key: item.key,
        name: item.name,
        region: item.region,
        price: item.price,
        time: item.time,
        sort1: item.sort1,
        // img: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
        state: (
          <Switch
            style={{
              marginBlockEnd: 16,
            }}
            checked={item.state}
            checkedChildren={item.state ? "启用" : "禁用"}
            unCheckedChildren={item.state ? "启用" : "禁用"}
            onChange={() => dis(pListItemStateChe(item.id))}
          />
        ),
      });
    }
  });

  const columns = [
    {
      title: "ID",
      dataIndex: "key",
      key: "key",
      width: 80,
    },
    {
      title: "楼盘名称",
      dataIndex: "name",
      width: 160,
      key: "name",
    },
    {
      title: "所属区域",
      dataIndex: "region",
      width: 100,
      key: "region",
    },
    {
      title: "价格",
      dataIndex: "price",
      width: 150,
      key: "price",
      sorter: (a, b) => a.price - b.price,
    },
    {
      title: "创建时间",
      dataIndex: "time",
      width: 140,
      key: "time",
    },

    {
      title: "排序",
      dataIndex: "sort1",
      width: 110,
      key: "sort1",
    },

    {
      disable: true,
      title: "状态",
      width: 110,
      dataIndex: "state",
      key: "state",
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: "select",
      key: "state",
    },
    {
      title: "沙盘",
      key: "sandTable",
      width: 80,
      valueType: "sandTable",
      render: (text, record) => [
        <img
          style={{ width: "50px", height: "50px" }}
          src="https://img2.baidu.com/it/u=2735887356,1630169057&fm=253&fmt=auto?w=500&h=500"
          alt=""
        />,
      ],
    },

    {
      title: "操作",
      key: "option",
      width: 120,
      valueType: "option",
      render: (text, record) => [
        <>
          <Button
            style={{ background: "#4096ff", color: "#fff" }}
            onClick={() => edit(record)}
          >
            编辑
          </Button>

          <Space>
            <Button
              style={{ background: "#4096ff", color: "#fff" }}
              onClick={() => del(record)}
            >
              {" "}
              删除
            </Button>
          </Space>
        </>,
      ],
      key: "action",
    },
  ];

  // 编辑
  const edit = (item) => {
    nav("/home/propertiesforsale/propertymanagement/addaproperty");
    dis(editProperty(item));
  };

  // 删除
  const del = (item) => {
    message.success("删除成功");
    dis(delProperty1(item));
  };

  // 搜索
  const [form] = Form.useForm();
  const [formLayout, setFormLayout] = useState("horizontal");
  const onFormLayoutChange = ({ layout }) => {
    setFormLayout(layout);
    console.log(onFormLayoutChange);
  };
  const formItemLayout =
    formLayout === "horizontal"
      ? {
        labelCol: {
          span: 4,
        },
        wrapperCol: {
          span: 14,
        },
      }
      : null;
  const buttonItemLayout =
    formLayout === "horizontal"
      ? {
        wrapperCol: {
          span: 14,
          offset: 4,
        },
      }
      : null;

  // 全选删除
  const onFinish = (values) => {
    console.log("Success:", values);
    dis(searchProperty1(values));
  };

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const start = () => {
    setLoading(true);
    // ajax request after empty completing
    setTimeout(() => {
      setSelectedRowKeys([]);
      setLoading(false);
    }, 1000);
  };
  const onSelectChange = (newSelectedRowKeys) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  // 全部删除
  const deleteRow = () => {
    message.success("删除成功");
    dis(deleRow(selectedRowKeys));
  };

  return (
    <div style={{ width: "100%", height: "100%" }}>
      <Form {...formItemLayout} form={form} layout="inline" onFinish={onFinish}>
        <Form.Item name="region" label="区域">
          <Select
            showSearch
            style={{
              width: 200,
            }}
            placeholder="--请选择--"
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? "").includes(input)
            }
            filterSort={(optionA, optionB) =>
              (optionA?.label ?? "")
                .toLowerCase()
                .localeCompare((optionB?.label ?? "").toLowerCase())
            }
            options={[
              {
                value: "海口",
                label: "海口",
              },
              {
                value: "三亚",
                label: "三亚",
              },
              {
                value: "深圳",
                label: "深圳",
              },
              {
                value: "厦门",
                label: "厦门",
              },
              {
                value: "上海",
                label: "上海",
              },
            ]}
          />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select
            showSearch
            style={{
              width: 200,
            }}
            placeholder="一 所有 一"
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? "").includes(input)
            }
            filterSort={(optionA, optionB) =>
              (optionA?.label ?? "")
                .toLowerCase()
                .localeCompare((optionB?.label ?? "").toLowerCase())
            }
            options={[
              {
                value: 1,
                label: "启用",
              },
              {
                value: 2,
                label: "禁用",
              },
            ]}
          />
        </Form.Item>
        <Form.Item name="name">
          <Input placeholder="输入关键词搜索" />
        </Form.Item>
        <Form.Item {...buttonItemLayout}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Button
          type="primary"
          style={{ marginLeft: "50px" }}
          onClick={deleteRow}
        >
          选择删除
        </Button>
      </Form>

      <div>
        <ProTable
          dataSource={tableListDataSource}
          rowKey="key"
          pagination={{
            pageSize: 8,
          }}
          columns={columns}
          search={false}
          dateFormatter="string"
          rowSelection={rowSelection}
        />
      </div>
    </div>
  );
};
